<?php
/**
 * 行业类型控制器
 */

declare (strict_types = 1);

namespace app\controller\customer;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class Industry extends BaseController
{
    /**
     * 查看行业类型列表
     */
    public function list()
    {
        try {
            $param = Request::param();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            
            $where = [];
            
            // 关键词搜索
            if (!empty($param['keywords'])) {
                $where[] = ['name', 'like', '%' . trim($param['keywords']) . '%'];
            }
            
            // 查询行业类型列表
            $list = Db::name('industry')
                ->where($where)
                ->page($page, $limit)
                ->select();
            
            // 查询总数
            $count = Db::name('industry')
                ->where($where)
                ->count();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $count
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 查看单个行业类型信息
     */
    public function view()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            $industry = Db::name('industry')
                ->where('id', $param['id'])
                ->find();
            
            if (empty($industry)) {
                return json(['code' => 404, 'msg' => '行业类型不存在']);
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $industry
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 设置行业类型（获取启用的行业列表）
     */
    public function set()
    {
        try {
            $list = Db::name('industry')
                ->where('status', 1)
                ->select();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 新建行业类型
     */
    public function add()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['name'])) {
            return json(['code' => 400, 'msg' => '行业名称不能为空']);
        }
        
        // 检查父级行业是否合法
        if (!empty($param['parent_id'])) {
            $parentIndustry = Db::name('industry')
                ->where('id', $param['parent_id'])
                ->find();
            
            if (empty($parentIndustry)) {
                return json(['code' => 400, 'msg' => '父级行业不存在']);
            }
        }
        
        $data = [
            'name' => $param['name'],
            'parent_id' => $param['parent_id'] ?? 0,
            'level' => $param['level'] ?? 1,
            'sort' => $param['sort'] ?? 0,
            'status' => $param['status'] ?? 1,
            'create_time' => time(),
            'update_time' => time()
        ];
        
        try {
            $industryId = Db::name('industry')->insertGetId($data);
            
            return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => $industryId]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '添加失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 编辑行业类型
     */
    public function edit()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        if (empty($param['name'])) {
            return json(['code' => 400, 'msg' => '行业名称不能为空']);
        }
        
        // 检查父级行业是否合法
        if (!empty($param['parent_id'])) {
            $parentIndustry = Db::name('industry')
                ->where('id', $param['parent_id'])
                ->find();
            
            if (empty($parentIndustry)) {
                return json(['code' => 400, 'msg' => '父级行业不存在']);
            }
            
            // 检查不能将行业设置为自己的子行业
            if ($param['id'] == $param['parent_id']) {
                return json(['code' => 400, 'msg' => '父级行业不能是该行业本身']);
            }
        }
        
        $data = [
            'id' => $param['id'],
            'name' => $param['name'],
            'parent_id' => $param['parent_id'] ?? 0,
            'level' => $param['level'] ?? 1,
            'sort' => $param['sort'] ?? 0,
            'status' => $param['status'] ?? 1,
            'update_time' => time()
        ];
        
        try {
            Db::name('industry')->update($data);
            
            return json(['code' => 0, 'msg' => '编辑成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '编辑失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除行业类型（软删除）
     */
    public function del()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            // 检查是否有子行业
            $childCount = Db::name('industry')
                ->where('parent_id', $param['id'])
                ->count();
            
            if ($childCount > 0) {
                return json(['code' => 400, 'msg' => '该行业下有子行业，不能删除']);
            }
            
            // 检查是否有客户属于此行业
            $customerCount = Db::name('customer')
                ->where('industry_id', $param['id'])
                // 移除不存在的delete_time条件
                ->count();
            
            if ($customerCount > 0) {
                return json(['code' => 400, 'msg' => '该行业下有客户，不能删除']);
            }
            
            Db::name('industry')
                ->where('id', $param['id'])
                ->update([
                    'status' => -1, // 使用status=-1表示删除状态
                    'update_time' => time()
                ]);
            
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
}